package com.thread.threadfirst.javaBase.java8;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

/**
 * 方法引用
 */
public class MethodReferencesTest {

    //Supplier是jdk1.8的函数式接口
    @FunctionalInterface
    public interface Supplier<T> {
        T get();
    }

    //Supplier是jdk1.8的接口，这里和lambda一起使用了
    public static MethodReferencesTest create(final Supplier<MethodReferencesTest> supplier) {
        return supplier.get();
    }

    public static void collide(final MethodReferencesTest car) {
        System.out.println("Collided " + car.toString());
    }

    public void follow(final MethodReferencesTest another) {
        System.out.println("Following the " + another.toString());
    }

    public void repair() {
        System.out.println("Repaired " + this.toString());
    }

    public static void main(String[] args) {

        //构造器引用：它的语法是Class::new，或者更一般的Class< T >::new实例如下：
        MethodReferencesTest methodReferencesTest1 = MethodReferencesTest.create(MethodReferencesTest::new);
        MethodReferencesTest methodReferencesTest2 = MethodReferencesTest.create(MethodReferencesTest::new);
        MethodReferencesTest methodReferencesTest3 = MethodReferencesTest.create(MethodReferencesTest::new);
        MethodReferencesTest methodReferencesTest4=new MethodReferencesTest();
        System.out.println("===================构造器引用========================");

        List<MethodReferencesTest> lists= Arrays.asList(methodReferencesTest1,methodReferencesTest2,methodReferencesTest3,methodReferencesTest4);

        //静态方法引用：它的语法是Class::static_method，实例如下：
        lists.forEach(MethodReferencesTest::collide);
        System.out.println("===================静态方法引用========================");

        //特定类的任意对象的方法引用：它的语法是Class::method实例如下：
        lists.forEach(MethodReferencesTest::repair);//不能调用follow(),提示信息：non-static method cannot be referenced from a static context 不能从静态上下文引用非静态方法
        System.out.println("==============特定类的任意对象的方法引用================");

        //特定对象的方法引用：它的语法是instance::method实例如下：
        MethodReferencesTest methodReferencesTest=MethodReferencesTest.create(MethodReferencesTest::new);
        lists.forEach(methodReferencesTest::follow);
        System.out.println("===================特定对象的方法引用===================");

        List list=new ArrayList();
        list.add("a");
        list.add("b");
        list.add("c");
        list.forEach(System.out::println);

    }
}
